//
//  ZRCrystalBall.m
//  简书:https://www.jianshu.com/u/043e94ca450f
//
//  Created by 黄涛 on 2018/1/12.
//  Copyright © 2018年 黄涛(ZR:zero). All rights reserved.

#import "ZRCrystalBall.h"
#import <CoreMotion/CoreMotion.h>
@interface ZRCrystalBall ()
{
    //物理仿真 动画
    UIDynamicAnimator * _dynamicAnimator;
    //物理仿真 行为
    UIDynamicItemBehavior * _dynamicItemBehavior;
    //重力 行为
    UIGravityBehavior * _gravityBechavior;
    //碰撞 行为
    UICollisionBehavior * _collisionBehavior;
}
/** 传感器 */
@property (nonatomic , strong) CMMotionManager * motionManager;

@end
@implementation ZRCrystalBall

- (instancetype)initWithFrame:(CGRect)frame showImages:(NSArray<UIImage*>*)images repeatShowImages:(NSArray<UIImage*>*)repeatImages{
    if (self = [super initWithFrame:frame]) {
        [self setupDynamic];
        [self setupGyroPush];
        for (UIImage * img in images) {
            int x = arc4random() % (int)self.frame.size.width; //随机X坐标
            //int size = arc4random() % 30 + 20;//随机大小
            CGFloat img_w = img.size.width;
            CGFloat img_h = img.size.height;
            UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, self.frame.size.height/2, img_w, img_h)];
            imageView.userInteractionEnabled = YES;
            imageView.image = img;
            [self addSubview:imageView];
            [_dynamicItemBehavior addItem:imageView];
            [_gravityBechavior addItem:imageView];
            [_collisionBehavior addItem:imageView];
        }
        
        for (UIImage * img in repeatImages) {
            
            int number = arc4random() % 4 + 1;
            for (int i = 0; i < number ; i++) {
                int x = arc4random() % (int)self.frame.size.width; //随机X坐标
                //int size = arc4random() % 30 + 20;//随机大小
                CGFloat img_w = img.size.width;
                CGFloat img_h = img.size.height;
                UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, self.frame.size.height/2, img_w, img_h)];
                imageView.userInteractionEnabled = YES;
                imageView.image = img;
                [self addSubview:imageView];
                [_dynamicItemBehavior addItem:imageView];
                [_gravityBechavior addItem:imageView];
                [_collisionBehavior addItem:imageView];
            }
        }
        
    }
    return self;
}

#pragma mark - 设置螺旋仪
- (void)setupGyroPush{
    
    self.motionManager = [[CMMotionManager alloc] init];
    //判断传感器是否可用
    if (![self.motionManager isGyroAvailable]) {
        !_failBlock ? : self.failBlock(GyroUnavailable);
    }else if (![self.motionManager isAccelerometerAvailable]){
        !_failBlock ? : self.failBlock(AccelerometerUnavailable);
    }else if(![self.motionManager isMagnetometerAvailable]){
        !_failBlock ? : self.failBlock(MagnetometerUnavailable);
    }
    
    //设备 运动 更新间隔
    self.motionManager.deviceMotionUpdateInterval = 1;
    [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
        double gravityX = motion.gravity.x;
        double gravityY = motion.gravity.y;
        // C 语言里 double atan2(double y,double x) 返回的是原点至点(x,y)的方位角，即与 x 轴的夹角。也可以理解为复数 x+yi 的辐角。返回值的单位为弧度，取值范围为  ；
        double xy = atan2(gravityX, gravityY);
        // 计算相对于y轴的重力方向
        self->_gravityBechavior.angle = xy - M_PI_2;
    }];
    
}
#pragma mark - 动态（动画设置）
- (void)setupDynamic{
    
    //创建实现动画 设定动画模拟区间 : self(地球)
    _dynamicAnimator = [[UIDynamicAnimator alloc] initWithReferenceView:self];
    //创建物理仿真行为
    _dynamicItemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[]];
    //设置弹性系数，数值越大，弹力越大
    _dynamicItemBehavior.elasticity = 0.5;
    //重力行为
    _gravityBechavior = [[UIGravityBehavior alloc] initWithItems:@[]];
    //碰撞行为
    _collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[]];
    //开始刚体碰撞(刚体:对象在物理系统的控制下来运动，刚体可接受外力与扭矩力用来保证游戏对象像在真实世界中那样进行运动)
    _collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
    
    //将 行为 添加到物理仿真动画中
    [_dynamicAnimator addBehavior:_dynamicItemBehavior];
    [_dynamicAnimator addBehavior:_gravityBechavior];
    [_dynamicAnimator addBehavior:_collisionBehavior];
    
}


@end
